<template>
  <section class="todoapp">
    <!-- 除了驼峰, 还可以使用-转换链接 -->
    <TodoHeader
      @addtask="addtaskfn"
      :list="list"
      @checkall="checkall"
    ></TodoHeader>
    <TodoMain :list="showlist" @dad="delfn" @change="fn"></TodoMain>
    <TodoFooter
      :list="list"
      @clear="clearfn"
      :type="type"
      @changetype="changetypefn"
    ></TodoFooter>
  </section>
</template>

<script>
// 1.0 样式引入
import './styles/base.css'
import './styles/index.css'

import TodoHeader from './components/TodoHeader'
import TodoMain from './components/TodoMain'
import TodoFooter from './components/TodoFooter'

export default {
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
  data() {
    return {
      list: JSON.parse(localStorage.getItem('todolist')) || [],
      type: 'all', // all表示全部，yes表示显示已完成，no表示显示未完成
    }
  },
  methods: {
    delfn(id) {
      this.list = this.list.filter((item) => item.id !== id)
    },
    fn(id) {
      const res = this.list.find((item) => item.id === id)
      res.isDone = !res.isDone
    },
    addtaskfn(task) {
      this.list.push({
        id: this.list.length ? this.list.at(-1).id + 1 : 100,
        name: task,
        isDone: false,
      })
    },
    clearfn() {
      this.list = this.list.filter((item) => !item.isDone)
     
    },
    changetypefn(type) {
      console.log(1)
      this.type = type
    },
    checkall(val) {
      this.list.forEach((item) => (item.isDone = val))
    },
  },
  computed: {
    showlist() {
      if (this.type === 'yes') {
        return (this.list = this.list.filter((item) => item.isDone))
      } else if (this.type === 'no') {
        return (this.list = this.list.filter((item) => !item.isDone))
      } else {
        return this.list
      }
    },
  },
  watch: {
    list: {
      deep: true,
      handler(newval) {
        localStorage.setItem('todolist', JSON.stringify(newval))
      },
    },
  },
}
</script>
